<template>
  <el-card class="list-page">
    <div class="list-h">
      <div>
        <el-button
          type="primary"
          @click="handleDetail(null, 1)"
          class="add-option"
          >新增申请</el-button
        >
      </div>
      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
      >
        <el-form-item label="建设单位" prop="factoryName">
          <el-input class="width-custom120" v-model="formInline.factoryName" />
        </el-form-item>

        <el-form-item label="物资申报单位" prop="companyName">
          <el-input class="width-custom120" v-model="formInline.companyName" />
        </el-form-item>
        <el-form-item label="物资出入类型" prop="accessType">
          <el-select
            class="width-custom140"
            v-model="formInline.accessType"
            clearable
            filterable
          >
            <el-option
              v-for="item in accessTypeList"
              :label="item.text"
              :key="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input class="width-custom120" v-model="formInline.licensePlate" />
        </el-form-item>
        <el-form-item label="审批状态" prop="approveStatus">
          <el-select
            class="width-custom140"
            v-model="formInline.approveStatus"
            clearable
            filterable
          >
            <el-option
              v-for="item in statusList"
              :label="item.text"
              :key="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="btn-wrap">
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            @click="handleSearch"
            v-auth="`/projects/purchase--query`"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton
      style="height: calc(100vh - 340px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      v-loading="loading"
      v-show="!loading"
      :height="'calc(100vh - 340px)'"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>

      <el-table-column type="index" label="序号" width="80">
        <template v-slot="scope">
          <span>{{
            (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="formNo" label="表单编号"> </el-table-column>
      <el-table-column prop="factoryName" width="120" label="出入单位">
      </el-table-column>
      <el-table-column
        width="120"
        prop="companyName"
        label="物资申报单位"
      ></el-table-column>
      <el-table-column width="120" prop="accessType" label="物资出入类型">
        <template #default="{ row }">
          <span>{{
            row.accessType === "EXIT_MATERIAL" ? "物资出厂" : "空车出厂"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="materialName" label="物资名称"> </el-table-column>
      <el-table-column prop="materialNum" label="物资数量"></el-table-column>
      <el-table-column prop="remainAmount" label="物资图片">
        <template #default="{ row }">
          <div class="img-box">
            <div
              class="img-item"
              v-for="(item, index) in (row.materialImgs || []).slice(0, 2)"
              :key="index"
            >
              <previewImg :files="item" type="epms"></previewImg>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="entryExitTime" label="进出场时间">
      </el-table-column>
      <el-table-column prop="licensePlates" label="车牌号">
        <template #default="{ row }">
          <span>{{ row.licensePlates.join(",") }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="approveStatus" label="审批状态">
        <template #default="{ row }">
          <span>{{ STATUS_MAP[row.approveStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="handleDetail(row, 0)"
            >查看</el-button
          >
          <el-button
            v-if="row.approveStatus === '0'"
            type="text"
            size="small"
            @click="handleDetail(row, 1)"
            >编辑</el-button
          >
          <el-button
            v-if="row.approveStatus === '2'"
            type="text"
            size="small"
            @click="showCode(row)"
            >放行码</el-button
          >
          <!-- <el-button
              type="text"
              size="small"
              @click="handleDownLoad(row, $index)"
              >下载</el-button
            > -->
          <el-button
            v-if="row.approveStatus === '0'"
            type="text"
            size="small"
            class="btns-danger"
            @click="showDeleteMessageBox(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <re-pagination
      v-if="total > 0"
      :total="total"
      v-model:page="pageState.pageNum"
      v-model:limit="pageState.pageSize"
      @pagination="handleChangePage"
    />

    <el-dialog
      :title="detailData.title"
      v-model="detailData.dialogFormVisible"
      destroy-on-close
      width="520px"
    >
      <purchase-detail
        :purId="detailData.purId"
        :methodList="methodList"
        :professionList="professionList"
        @emitClose="detailData.dialogFormVisible = false"
        @updateClose="updateClose"
      />
    </el-dialog>

    <relation-project
      v-if="relationData.isShowRelation"
      :relationInfo="relationData.data"
      @updateClose="updateClose"
      @handleCancel="relationData.isShowRelation = false"
    ></relation-project>

    <import-dom
      v-if="showImport"
      ref="importRef"
      @cancel="showImport = false"
      @submit="submitImport"
    ></import-dom>
    <el-dialog
      title="放行二维码"
      v-model="codeDialog"
      destroy-on-close
      width="420px"
    >
      <div
        style="
          width: 420px;
          height: 320px;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <qrcode-vue :value="qrcodeUrl" size="200"></qrcode-vue>
      </div>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import RePagination from "/@/components/RePagination/index.vue";
import { accessList, delAccess, getAccessInfo } from "/@/api/vehicle";
import { postDictList } from "/@/api/home";
// import purchaseDetail from "./components/purchaseDetail.vue";
// import relationProject from "./components/relationProject.vue";
// import importDom from "./components/import.vue";
import { ElMessageBox } from "element-plus";
import NotifMessage from "/@/utils/message/notification";
// import { exportExcel } from "/@/utils/file";
import { importCenPurchas } from "/@/api/projects";
import { useRouter } from "vue-router";
import previewImg from "/@/components/previewImg/index.vue";
import QrcodeVue from "qrcode.vue";

const router = useRouter();
const formRef = ref<HTMLFormElement | null>(null) as any;
const importRef = ref<HTMLFormElement | null>(null) as any;
const initData = {
  factoryName: "",
  companyName: "",
  accessType: "",
  licensePlate: "",
  approveStatus: ""
};
const formInline = reactive(initData);
const timeValue = ref(null);
const methodList = ref([]);
const professionList = ref([]);
const statusList = ref([
  { text: "草稿", value: "0" },
  { text: "审批中", value: "1" },
  { text: "审核完成", value: "2" },
  { text: "终止", value: "3" },
  { text: "待提交", value: "4" },
  { text: "已完成", value: "5" }
]);
const accessTypeList = ref([
  { text: "物资出厂", value: "EXIT_MATERIAL" },
  { text: "空车出厂", value: "EXIT_EMPTY" }
]);
const showImport = ref(false);
const itemList = [
  // { key: methodList, value: "thd_cen_pro_method" },
  // { key: professionList, value: "thd_cen_profession_dir" }
  // { key: statusList, value: "thd_cen_current_state" }
];
const qrcodeUrl = ref("");
const codeDialog = ref(false);
const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});
const tableData = ref([]);
const total = ref<number>(0);
const loading = ref<boolean>(false);
const formParams = ref<typeof initData>({ ...initData });
const detailData = reactive({
  type: 1,
  purId: "",
  dialogFormVisible: false,
  title: "新增集采项目"
});
const relationData = reactive({
  isShowRelation: false,
  index: 0,
  data: {}
});
// 状态 0 草稿 1 审批中 2 审核完成 3 终止 4 待提交
const STATUS_MAP = {
  0: "草稿",
  1: "审批中",
  2: "审核完成",
  3: "终止",
  4: "待提交",
  5: "已完成"
};

//获取数据列表
const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await accessList({
      ...obj,
      ...pageState
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
      if (relationData.isShowRelation) {
        if (tableData.value?.length) {
          //编辑新增关联项目时，实时更新该项目的剩余预算
          relationData.data = tableData.value[relationData.index];
        }
      }
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};
// const handleDownLoad = async row => {
//   console.log(row);
// };
//新增编辑集采项目
const handleDetail = async (item, isEdit) => {
  router.replace({
    path: "/projects/vehicle/access/detail",
    query: {
      id: item && item.id,
      isEdit
    }
  });
};

const updateClose = async () => {
  getTableList(formInline);
  detailData.dialogFormVisible = false;
};

const showDeleteMessageBox = row => {
  ElMessageBox.confirm("确定删除该条记录吗？", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    iconClass: "el-icon-warning"
  })
    .then(() => {
      handleDelete(row);
    })
    .catch(() => {});
};
const showCode = async row => {
  try {
    console.log("id", row.id);
    const { code, message, data } = await getAccessInfo({ id: row.id });
    if (code === 200) {
      console.log("----------detail", data);
      codeDialog.value = true;
      qrcodeUrl.value = data.qrCodeUrl;
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
const handleDelete = async row => {
  try {
    console.log("id", row.id);
    const { code, message } = await delAccess(row.id);
    if (code === 200) {
      NotifMessage.success(message);
      getTableList(formInline);
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 数据字典
const initPostDictList = async item => {
  try {
    const { data } = await postDictList({ dicType: item.value });
    item["key"].value = data;
  } catch (err) {
    console.log(err);
  }
};

//改变时间
const handleChangeDate = item => {
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  formParams.value = initData;
  handleChangeDate(null);
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

const submitImport = async formData => {
  try {
    const { code, message } = await importCenPurchas(formData);
    if (code === 200) {
      NotifMessage.success(message);
      showImport.value = false;
      handleSearch();
    } else {
      NotifMessage.error(message || "请重试");
    }
  } catch (err) {
    importRef.value.handleRemove();
  }
};

// const exportFunc = async () => {
//   let formData = {
//     ...formInline,
//     pageNum: 1,
//     pageSize: 0
//   };
//   exportExcel("/snow-admin/cenPurchas/export", formData, `集采项目`);
// };

onMounted(() => {
  itemList.forEach(item => {
    initPostDictList(item);
  });
});
getTableList(formInline);
</script>

<style>
.img-box {
  display: flex;
}
.img-item {
  margin-right: 4px;
  max-height: 44px;
}
.el-icon-question {
  color: #ffc069;
}
.el-icon-warning {
  color: #e45d5d !important;
}
</style>

<style scoped lang="scss">
.text-danger {
  color: #e45d5d;
}
</style>
